package org.example.config;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.example.ZookeeperProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

/**
 * @author shenguangyang
 */
@Configuration
public class ZookeeperConfig {
    private static final Logger log = LoggerFactory.getLogger(ZookeeperConfig.class);
    @Resource
    private ZookeeperProperties zookeeperProperties;

    @Bean(name = "zkClient")
    public ZooKeeper zkClient() {
        String address = zookeeperProperties.getAddress();
        int sessionTimeout = zookeeperProperties.getSessionTimeout();
        ZooKeeper zooKeeper = null;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            // 连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            // 可指定多台服务地址 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
            zooKeeper = new ZooKeeper(address, sessionTimeout, event -> {
                if (Watcher.Event.KeeperState.SyncConnected == event.getState()) {
                    //如果收到了服务端的响应事件,连接成功
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            log.info("init zooKeeper connection success , state is: {}", zooKeeper.getState());

        } catch (Exception e) {
            log.error("init zooKeeper connection error: ", e);
        }
        return zooKeeper;
    }
}
